package com.live.webvideo.common.util;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.live.webvideo.common.cache.Cache;
import com.live.webvideo.common.cache.CacheManager;
import org.apache.commons.httpclient.HttpException;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class ToolUtil {

    //文件响应下载
    public static void downloadFile(File file, OutputStream out) {
        try {
            FileInputStream ins = new FileInputStream(file);
            System.out.println("ins--------" + ins);
            byte[] b = new byte[1024];
            int n = 0;
            while ((n = ins.read(b)) != -1) {
                out.write(b, 0, n);
                System.out.println("b---------" + b);
            }

            ins.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //集合分页
    public static List<Map> listSplit(int page, int limit, List<Map> list) {

        List<Map> result = new ArrayList<Map>();
        if (list != null && list.size() > 0) {
            int allCount = list.size();
            int pageCount = (allCount + limit - 1) / limit;
            if (page >= pageCount) {
                page = pageCount;
            }
            int start = (page - 1) * limit;
            int end = page * limit;
            if (end >= allCount) {
                end = allCount;
            }
            for (int i = start; i < end; i++) {
                result.add(list.get(i));
            }
        }

        return (result != null && result.size() > 0) ? result : new ArrayList<>();

    }


    /**
     * 计算距离现在时间
     * @return
     */
    public static Long getBetweenTimes(String time) {
        long betweenDays = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date plansdate = sdf.parse(time);//预计完成时间

            Calendar calendar = new GregorianCalendar();
            calendar.setTime(plansdate);
            //当前时间
            Date smdate = new Date();

            smdate = sdf.parse(sdf.format(smdate));
            Calendar cal = Calendar.getInstance();
            cal.setTime(smdate);
            long time1 = cal.getTimeInMillis();
            cal.setTime(calendar.getTime());
            long time2 = cal.getTimeInMillis();
            betweenDays = ((time2 - time1) / (1000 * 3600 * 24));//天数

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return betweenDays;
    }

    /**
     * 计算两个时间间隔天数
     * @return
     */
    public static Long getBetweenDays(String startTime,String endTime) {
        long betweenDays = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date endTimeN = sdf.parse(startTime);//结束时间
            Date plansdate = sdf.parse(endTime);//开始时间

            Calendar calendar = new GregorianCalendar();
            calendar.setTime(plansdate);

            Date smdate = sdf.parse(sdf.format(endTimeN));
            Calendar cal = Calendar.getInstance();
            cal.setTime(smdate);
            long time1 = cal.getTimeInMillis();
            cal.setTime(calendar.getTime());
            long time2 = cal.getTimeInMillis();
            betweenDays = ((time2 - time1) / (1000 * 3600 * 24));//天数

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return betweenDays;
    }

    /**
     * 分页参数结果
     * @param pageInfo
     * @param current
     * @param pageSize
     * @return
     */
    public static RdPage getPage(PageInfo pageInfo, int current, int pageSize) {
        RdPage rdPage = new RdPage();
        //分页信息
        rdPage.setTotal(pageInfo.getTotal());
        rdPage.setPages(pageInfo.getPages());
        rdPage.setCurrent(Integer.valueOf(current));
        rdPage.setPageSize(Integer.valueOf(pageSize));

        return rdPage;
    }

    /**
     * 判断缓存是否存在
     */
    public static String cacheExist(String user_id) {
        String key = user_id;
        Cache cache = CacheManager.getCacheInfo(key);
        if (null == cache || cache.getValue() == null) {
            cache = new Cache();
            cache.setKey(key);
            cache.setValue(1);
            CacheManager.putCache(key, cache);

            return "empty";
        } else {
            return "full";
        }
    }

    //发送短信
    public static String sendMsg(String phone,String content)  throws HttpException, IOException{
        try {
            //创建连接
            URL url = new URL("http://120.27.195.107:8181/api/sms");
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            //application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据 application/json;charset=utf-8 -> json数据
            connection.setRequestProperty("Content-Type",
                    "application/json;charset=utf-8");
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            connection.connect();

            //POST请求
            OutputStream out = connection.getOutputStream();
            JSONObject obj = new JSONObject();
            obj.put("tel", phone);
            obj.put("Content", content);

            //String postData = "{\"tel\":"+phone+",\"Content\":"+content+"}";
            //String postData = "{\"tel\":\"13685515856\",\"Content\":\"蓝色666\"}";
            out.write(obj.toJSONString().getBytes("utf-8"));
            out.flush();
            out.close();

            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String lines;
            StringBuffer sb = new StringBuffer();
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            System.out.println(sb);
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";

    }

    //发送邮件
    public static String sendEmial(String tomail,String title,String content)  throws HttpException, IOException{
        try {
            //创建连接
            URL url = new URL("http://120.27.195.107:8181/api/EMaill");
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            //application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据 application/json;charset=utf-8 -> json数据
            connection.setRequestProperty("Content-Type",
                    "application/json;charset=utf-8");
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            connection.connect();

            //POST请求
            OutputStream out = connection.getOutputStream();
            JSONObject obj = new JSONObject();
            obj.put("Tomail", tomail);
            obj.put("Title", title);
            obj.put("Content", content);

            out.write(obj.toJSONString().getBytes("utf-8"));
            out.flush();
            out.close();

            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String lines;
            StringBuffer sb = new StringBuffer();
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            System.out.println(sb);
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";

    }

    /**
     * 获取6位随机数
     *
     * @return
     */
    public static String getCode() {

        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);

        return verifyCode;
    }

    /**
     * 获取8位随机数
     *
     * @return
     */
    public static String getCodeEight() {

        String verifyCode = String.valueOf(new Random().nextInt(89999999) + 10000000);

        return verifyCode;
    }

}
